<template>
  <!-- 告警管理 -->
  <div class="Hcont" v-if="homepage === 6">
    <div class="Hhead" @click="toHcont">
      <div class="hd1">
        <img src="../assets/logo3.png" alt="智能配送系统" class="hd11">
        <div class="hd12 noselect">
          <div class="hd121">智能配送</div>
          <div class="hd122">Intelligent Distribution</div>
        </div>
      </div>
      <img src="../assets/work.png" alt="系统状态" class="hd2">
      <div class="hd4"></div>
      <div class="hd3">
        <img src="../assets/tou.png" alt="用户头像" class="hd31">
        <el-dropdown @command="handleDropdownCommand">
          <span class="el-dropdown-link noselect xiaoshou" @click.stop>
            Qin<el-icon class="el-icon--right"><ArrowDown /></el-icon>
        </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :icon="Postcard" command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item :icon="User" command="customer">AI客服</el-dropdown-item>
              <el-dropdown-item :icon="Setting" command="setting">设置</el-dropdown-item>
              <el-dropdown-item :icon="Switch" command="switchAccount">切换账号</el-dropdown-item>
              <el-dropdown-item :icon="SwitchButton" command="logout" divided>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="hb"></div>
    <div class="Hbody">
      <div class="bdl">
        <div class="bdl1">
          <div class="bdl11 noselect xiaoshou" @click="uav" :class="{ 'active-nav': homepage === 2 }">
            <img src="../assets/UAV.png" alt="无人机管理" class="bdl111">
            <div class="bdl112">无人机管理</div>
          </div>
          <div class="bdl12 noselect xiaoshou" @click="mm" :class="{ 'active-nav': homepage === 3 }">
            <img src="../assets/MM.png" alt="商户管理" class="bdl121">
            <div class="bdl122">商户管理</div>
          </div>
          <div class="bdl13 noselect xiaoshou" @click="task" :class="{ 'active-nav': homepage === 4 }">
            <img src="../assets/task.png" alt="任务管理" class="bdl131">
            <div class="bdl132">任务管理</div>
          </div>
          <div class="bdl14 noselect xiaoshou" @click="map" :class="{ 'active-nav': homepage === 5 }">
            <img src="../assets/map.png" alt="地图与空域管理" class="bdl141">
            <div class="bdl142">地图与空域管理</div>
          </div>
          <div class="bdl15 noselect xiaoshou" @click="alarm" :class="{ 'active-nav': homepage === 6 }">
            <img src="../assets/alarm.png" alt="告警中心" class="bdl151">
            <div class="bdl152">告警中心</div>
          </div>
        </div>
      </div>

      <div class="bdr">
        <div class="alarm-dashboard">
          <!-- 告警概览统计 -->
          <div class="alarm-overview">
            <div class="overview-card critical">
              <div class="overview-icon">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="overview-info">
                <div class="overview-value">{{ criticalAlerts }}</div>
                <div class="overview-label">紧急告警</div>
              </div>
              <div class="overview-progress">
                <el-progress 
                  :percentage="criticalProgress" 
                  stroke-width="6" 
                  stroke-color="#F56C6C"
                ></el-progress>
              </div>
            </div>
            <div class="overview-card high">
              <div class="overview-icon">
                <el-icon><ExclamationTriangle /></el-icon>
              </div>
              <div class="overview-info">
                <div class="overview-value">{{ highAlerts }}</div>
                <div class="overview-label">高级告警</div>
              </div>
              <div class="overview-progress">
                <el-progress 
                  :percentage="highProgress" 
                  stroke-width="6" 
                  stroke-color="#E6A23C"
                ></el-progress>
              </div>
            </div>
            <div class="overview-card medium">
              <div class="overview-icon">
                <el-icon><InfoFilled /></el-icon>
              </div>
              <div class="overview-info">
                <div class="overview-value">{{ mediumAlerts }}</div>
                <div class="overview-label">中级告警</div>
              </div>
              <div class="overview-progress">
                <el-progress 
                  :percentage="mediumProgress" 
                  stroke-width="6" 
                  stroke-color="#409EFF"
                ></el-progress>
              </div>
            </div>
            <div class="overview-card low">
              <div class="overview-icon">
                <el-icon><HelpFilled /></el-icon>
              </div>
              <div class="overview-info">
                <div class="overview-value">{{ lowAlerts }}</div>
                <div class="overview-label">低级告警</div>
              </div>
              <div class="overview-progress">
                <el-progress 
                  :percentage="lowProgress" 
                  stroke-width="6" 
                  stroke-color="#67C23A"
                ></el-progress>
              </div>
            </div>
            <div class="overview-card total">
              <div class="overview-icon">
                <el-icon><Bell /></el-icon>
              </div>
              <div class="overview-info">
                <div class="overview-value">{{ totalAlerts }}</div>
                <div class="overview-label">今日总告警</div>
              </div>
              <div class="overview-handle">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="handleAllAlerts"
                  :disabled="!hasPendingAlerts"
                >
                  处理全部
                </el-button>
              </div>
            </div>
          </div>

          <!-- 告警趋势图表 -->
          <div class="alarm-chart">
            <el-card>
              <template #header>
                <div class="chart-header">
                  <span>告警趋势分析（近7天）</span>
                  <el-select  
                    v-model="chartTimeRange" 
                    size="small" 
                    @change="refreshChartData"
                  >
                    <el-option label="近7天" value="7d"></el-option>
                    <el-option label="近30天" value="30d"></el-option>
                    <el-option label="近90天" value="90d"></el-option>
                  </el-select>
                </div>
              </template>
              <el-chart :auto-resize="true" class="chart-container">
                <el-line-series 
                  :data="chartData.series" 
                  :x-field="'date'" 
                  :y-field="'count'"
                  :point="true"
                  :smooth="true"
                ></el-line-series>
                <el-axis 
                  :orient="'bottom'" 
                  :field="'date'"
                  :title="'日期'"
                ></el-axis>
                <el-axis 
                  :orient="'left'" 
                  :field="'count'"
                  :title="'告警数量'"
                ></el-axis>
                <el-tooltip 
                  :formatter="chartTooltipFormatter"
                  :show-markers="true"
                ></el-tooltip>
              </el-chart>
            </el-card>
          </div>
          <!-- 告警筛选与操作 -->
          <div class="alarm-controls">
            <div class="filter-group">
              <el-select 
                v-model="selectedSeverity" 
                placeholder="选择告警级别" 
                size="small"
                class="filter-select"
                @change="filterAlerts"
              >
                <el-option label="全部级别" value="all"></el-option>
                <el-option label="紧急告警" value="CRITICAL"></el-option>
                <el-option label="高级告警" value="HIGH"></el-option>
                <el-option label="中级告警" value="MEDIUM"></el-option>
                <el-option label="低级告警" value="LOW"></el-option>
              </el-select>
              <el-select 
                v-model="selectedType" 
                placeholder="选择告警类型" 
                size="small"
                class="filter-select"
                @change="filterAlerts"
              >
                <el-option label="全部类型" value="all"></el-option>
                <el-option label="飞行安全" value="flight"></el-option>
                <el-option label="设备状态" value="device"></el-option>
                <el-option label="环境风险" value="environment"></el-option>
                <el-option label="任务异常" value="task"></el-option>
              </el-select>
              <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                size="small"
                class="filter-date"
                @change="filterAlerts"
              ></el-date-picker>
            </div>
            <div class="action-group">
              <el-button 
                type="primary" 
                size="small" 
                @click="refreshAlerts"
                :loading="isRefreshing"
              >
                <Refresh :spin="isRefreshing" /> 刷新
              </el-button>
              <el-button 
                type="success" 
                size="small" 
                @click="handleAutoResolve"
                :disabled="!hasAutoResolvable"
              >
                <MagicStick /> 自动处理
              </el-button>
              <el-button 
                type="warning" 
                size="small" 
                @click="exportAlertReport"
                :disabled="totalAlerts === 0"
              >
                <Download /> 导出报告
              </el-button>
            </div>
          </div>

          <!-- 告警列表 -->
          <div class="alarm-list">
            <el-table 
              :data="filteredAlerts" 
              border 
              size="small"
              class="alarm-table"
              @row-click="handleRowClick"
              v-loading="tableLoading"
              empty-text="暂无告警数据"
              empty-state="empty-alarm"
              @selection-change="handleSelectionChange"
            >
              <el-table-column 
                type="selection" 
                width="40"
                :selectable="row => row.status === 'pending'"
              ></el-table-column>
              <el-table-column 
                type="index" 
                label="序号" 
                width="60"
                align="center"
              ></el-table-column>
              <el-table-column 
                prop="id" 
                label="告警ID" 
                width="120"
              ></el-table-column>
              <el-table-column 
                prop="severity" 
                label="级别" 
                width="90"
              >
                <template #default="scope">
                  <el-tag 
                    :type="getSeverityTagType(scope.row.severity)"
                  >
                    {{ getSeverityText(scope.row.severity) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column 
                prop="type" 
                label="类型" 
                width="100"
              >
                <template #default="scope">
                  <el-tag type="info">{{ getTypeText(scope.row.type) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column 
                prop="title" 
                label="告警标题" 
                min-width="200"
              ></el-table-column>
              <el-table-column 
                prop="source" 
                label="来源" 
                width="120"
              ></el-table-column>
              <el-table-column 
                prop="timestamp" 
                label="发生时间" 
                width="180"
                sortable
              ></el-table-column>
              <el-table-column 
                prop="status" 
                label="状态" 
                width="100"
                sortable
              >
                <template #default="scope">
                  <el-tag 
                    :type="getStatusTagType(scope.row.status)"
                  >
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column 
                label="操作" 
                width="180"
              >
                <template #default="scope">
                  <el-button 
                    type="text" 
                    size="small" 
                    @click="viewAlertDetail(scope.row)"
                    class="view-btn"
                  >
                    详情
                  </el-button>
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="handleAlert(scope.row)"
                    :disabled="scope.row.status !== 'pending'"
                  >
                    处理
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 批量操作栏 -->
            <div class="batch-operation" v-if="selectedRows.length > 0">
              <span>已选择 {{ selectedRows.length }} 条记录</span>
              <el-button 
                type="primary" 
                size="small" 
                @click="handleBatchProcess"
              >
                批量处理
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="clearSelection"
              >
                取消选择
              </el-button>
            </div>

            <!-- 分页 -->
            <div class="pagination">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pageSize"
                :total="filteredAlerts.length"
                layout="total, sizes, prev, pager, next, jumper"
              ></el-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 告警详情弹窗 -->
    <el-dialog 
      v-model="detailVisible" 
      title="告警详情" 
      :width="700"
      :before-close="closeDetailDialog"
    >
      <div v-if="selectedAlert" class="alert-detail">
        <div class="detail-header">
          <div class="detail-title">
            <span>{{ selectedAlert.title }}</span>
            <el-tag 
              :type="getSeverityTagType(selectedAlert.severity)"
              class="detail-severity"
            >
              {{ getSeverityText(selectedAlert.severity) }}
            </el-tag>
          </div>
          <div class="detail-meta">
            <div class="meta-item">告警ID: {{ selectedAlert.id }}</div>
            <div class="meta-item">发生时间: {{ selectedAlert.timestamp }}</div>
            <div class="meta-item">来源: {{ selectedAlert.source }}</div>
            <div class="meta-item">状态: 
              <el-tag 
                :type="getStatusTagType(selectedAlert.status)"
              >
                {{ getStatusText(selectedAlert.status) }}
              </el-tag>
            </div>
          </div>
        </div>

        <div class="detail-content">
          <div class="content-section">
            <h3 class="section-title">告警描述</h3>
            <p class="section-content">{{ selectedAlert.description }}</p>
          </div>

          <div class="content-section">
            <h3 class="section-title">影响评估</h3>
            <el-descriptions column="1" border class="impact-descriptions">
              <el-descriptions-item label="受影响无人机">
                <span v-for="drone in selectedAlert.affectedDrones" :key="drone">
                  {{ drone }}
                  <el-divider direction="vertical" v-if="!$last"></el-divider>
                </span>
              </el-descriptions-item>
              <el-descriptions-item label="影响范围">{{ selectedAlert.impactRange }}</el-descriptions-item>
              <el-descriptions-item label="预计损失">{{ selectedAlert.potentialLoss }}</el-descriptions-item>
              <el-descriptions-item label="关联告警">
                <span v-if="selectedAlert.relatedAlerts.length > 0">
                  <el-link 
                    v-for="alert in selectedAlert.relatedAlerts" 
                    :key="alert" 
                    @click="jumpToAlert(alert)"
                  >
                    {{ alert }}
                    <span v-if="!$last">, </span>
                  </el-link>
                </span>
                <span v-else>无</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="content-section">
            <h3 class="section-title">推荐处理方案</h3>
            <div class="solution-card">
              <div class="solution-title">
                <span>系统推荐方案</span>
                <el-tag type="success">自动可处理</el-tag>
              </div>
              <p class="solution-content">{{ selectedAlert.recommendedSolution }}</p>
              <div class="solution-actions">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="adoptRecommendedSolution"
                  v-if="selectedAlert.status === 'pending'"
                >
                  采用推荐方案
                </el-button>
              </div>
            </div>
          </div>

          <div class="content-section" v-if="selectedAlert.status !== 'pending'">
            <h3 class="section-title">处理记录</h3>
            <el-timeline>
              <el-timeline-item 
                v-for="record in selectedAlert.handleRecords" 
                :key="record.timestamp"
                :timestamp="record.timestamp"
                :type="record.type"
              >
                <div class="timeline-content">
                  <div class="record-operator">操作员: {{ record.operator }}</div>
                  <div class="record-action">{{ record.action }}</div>
                  <div class="record-notes">{{ record.notes }}</div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button 
          type="primary" 
          @click="handleAlertInDetail"
          v-if="selectedAlert && selectedAlert.status === 'pending'"
        >
          处理告警
        </el-button>
      </template>
    </el-dialog>

    <!-- 告警处理弹窗 -->
    <el-dialog 
      v-model="handleVisible" 
      title="处理告警" 
      :width="500"
    >
      <div v-if="selectedAlert" class="handle-alert">
        <div class="handle-info">
          <p><strong>告警标题:</strong> {{ selectedAlert.title }}</p>
          <p><strong>告警级别:</strong> 
            <el-tag 
              :type="getSeverityTagType(selectedAlert.severity)"
            >
              {{ getSeverityText(selectedAlert.severity) }}
            </el-tag>
          </p>
          <p><strong>发生时间:</strong> {{ selectedAlert.timestamp }}</p>
        </div>

        <div class="handle-form">
          <el-form :model="handleForm" ref="handleFormRef" label-width="80px" :rules="handleFormRules">
            <el-form-item label="处理方式" prop="method" required>
              <el-radio-group v-model="handleForm.method">
                <el-radio label="auto">自动处理（系统推荐方案）</el-radio>
                <el-radio label="manual">手动处理（自定义方案）</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item 
              label="处理备注" 
              prop="notes" 
              required
            >
              <el-input 
                type="textarea" 
                v-model="handleForm.notes" 
                rows="4" 
                placeholder="请输入处理过程和结果..."
              ></el-input>
            </el-form-item>
            <el-form-item label="处理结果" prop="result" required>
              <el-radio-group v-model="handleForm.result">
                <el-radio label="resolved">已解决</el-radio>
                <el-radio label="partially">部分解决</el-radio>
                <el-radio label="unresolved">未解决（需升级）</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footer>
        <el-button @click="handleVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmHandleAlert"
          :loading="isHandling"
        >
          确认处理
        </el-button>
      </template>
    </el-dialog>

    <!-- 批量处理弹窗 -->
    <el-dialog 
      v-model="batchHandleVisible" 
      title="批量处理告警" 
      :width="500"
    >
      <div class="batch-handle-form">
        <p class="batch-count">将批量处理 <span class="count-number">{{ selectedRows.length }}</span> 条待处理告警</p>
        
        <el-form :model="batchHandleForm" ref="batchFormRef" label-width="80px" :rules="batchHandleRules">
          <el-form-item label="处理方式" prop="method" required>
            <el-radio-group v-model="batchHandleForm.method">
              <el-radio label="auto">自动处理（系统推荐方案）</el-radio>
              <el-radio label="manual">统一手动处理</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item 
            label="处理备注" 
            prop="notes" 
            required
          >
            <el-input 
              type="textarea" 
              v-model="batchHandleForm.notes" 
              rows="4" 
              placeholder="请输入批量处理备注..."
            ></el-input>
          </el-form-item>
          <el-form-item label="处理结果" prop="result" required>
            <el-radio-group v-model="batchHandleForm.result">
              <el-radio label="resolved">已解决</el-radio>
              <el-radio label="partially">部分解决</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="batchHandleVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmBatchHandle"
          :loading="isBatchHandling"
        >
          确认批量处理
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref, computed, onMounted, reactive } from 'vue'
import { 
  ArrowDown, Postcard, User, Setting, Switch, SwitchButton,
  Warning, ExclamationTriangle, InfoFilled, HelpFilled,
  Refresh, MagicStick, Download, Bell
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElNotification, ElDivider, ElLink, ElChart, ElLineSeries, ElAxis, ElTooltip } from 'element-plus'

// 路由实例
const router = useRouter()

// 页面状态管理
const homepage = ref(6) // 当前为告警中心页面

// 导航方法
const toHcont = () => {
  homepage.value = 1
  router.push('/HomeViews')
}
const uav = () => { 
  homepage.value = 2
  router.push('/navViews') 
}
const mm = () => { 
  homepage.value = 3
  router.push('/mmViews') 
}
const task = () => { 
  homepage.value = 4 
  router.push('/taskViews')
}
const map = () => { 
  homepage.value = 5
  router.push('/mapViews')
}
const alarm = () => { 
  homepage.value = 6
  router.push('/alarmViews') 
}
const customer = () => { 
  router.push("/chatViews") 
}

// 下拉菜单命令处理
const handleDropdownCommand = (command) => {
  switch(command) {
    case 'profile':
      ElMessage.info('个人信息功能待实现')
      break
    case 'customer':
      customer()
      break
    case 'setting':
      ElMessage.info('设置功能待实现')
      break
    case 'switchAccount':
      ElMessage.info('切换账号功能待实现')
      break
    case 'logout':
      ElMessageBox.confirm(
        '确定要退出登录吗？',
        '退出确认',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        router.push('/login')
        ElMessage.success('已退出登录')
      })
      break
  }
}

// 告警数据
const alerts = ref([
  {
    id: 'ALM-20250715-001',
    severity: 'CRITICAL',
    type: 'flight',
    title: '无人机UAV-003与UAV-007碰撞风险',
    source: '空域监控系统',
    timestamp: '2025-07-15 09:23:45',
    status: 'pending',
    description: '无人机UAV-003与UAV-007当前距离45米，相对速度12m/s，预计碰撞时间(TTC)为3.7秒，存在极高碰撞风险。',
    affectedDrones: ['UAV-003', 'UAV-007'],
    impactRange: '市中心商业区空域',
    potentialLoss: '可能导致设备损坏和地面人员受伤',
    relatedAlerts: [],
    recommendedSolution: '立即指令UAV-003爬升20米，UAV-007下降10米，形成高度差规避碰撞风险。',
    handleRecords: []
  },
  {
    id: 'ALM-20250715-002',
    severity: 'HIGH',
    type: 'device',
    title: '无人机UAV-012电池电量告急',
    source: '无人机传感器',
    timestamp: '2025-07-15 09:18:22',
    status: 'pending',
    description: '无人机UAV-012当前电量8%，低于10%阈值，无法完成剩余配送任务，需要紧急处理。',
    affectedDrones: ['UAV-012'],
    impactRange: '东部配送区域',
    potentialLoss: '配送任务失败，无人机可能迫降',
    relatedAlerts: [],
    recommendedSolution: '立即启动紧急返航程序，引导至最近的充电站点进行充电。',
    handleRecords: []
  },
  {
    id: 'ALM-20250715-003',
    severity: 'MEDIUM',
    type: 'environment',
    title: '西北部区域突发大风预警',
    source: '气象服务',
    timestamp: '2025-07-15 09:05:10',
    status: 'processed',
    description: '西北部区域风速已达14m/s，接近15m/s的危险阈值，可能影响无人机稳定性。',
    affectedDrones: ['UAV-005', 'UAV-009', 'UAV-011'],
    impactRange: '西北部空域',
    potentialLoss: '无人机可能偏离航线，任务延误',
    relatedAlerts: [],
    recommendedSolution: '暂时限制西北部区域新任务起飞，已在该区域的无人机降低至100米以下高度飞行。',
    handleRecords: [
      {
        timestamp: '2025-07-15 09:07:30',
        type: 'success',
        operator: '系统自动处理',
        action: '已执行推荐方案，限制新任务并调整飞行高度',
        notes: '当前区域无人机均已响应指令，状态稳定'
      }
    ]
  },
  {
    id: 'ALM-20250715-004',
    severity: 'LOW',
    type: 'task',
    title: '任务TSK-20250715-032预计延误',
    source: '任务管理器',
    timestamp: '2025-07-15 08:55:33',
    status: 'pending',
    description: '任务TSK-20250715-032由于前期配送点调整，预计送达时间将延迟12分钟，超出标准时效。',
    affectedDrones: ['UAV-008'],
    impactRange: '南部配送区域',
    potentialLoss: '客户满意度下降',
    relatedAlerts: [],
    recommendedSolution: '向客户发送延误通知并提供优惠券补偿，调度附近空闲无人机协助配送。',
    handleRecords: []
  },
  {
    id: 'ALM-20250715-005',
    severity: 'HIGH',
    type: 'flight',
    title: '无人机UAV-005进入禁飞区',
    source: '空域监控系统',
    timestamp: '2025-07-15 08:40:15',
    status: 'processed',
    description: '无人机UAV-005已进入机场禁飞区边界，距离核心禁飞区100米，违反空域管理规定。',
    affectedDrones: ['UAV-005'],
    impactRange: '机场周边空域',
    potentialLoss: '违反航空管理规定，可能面临处罚',
    relatedAlerts: [],
    recommendedSolution: '立即指令无人机退出禁飞区，调整至备用航线，记录违规原因并上报监管部门。',
    handleRecords: [
      {
        timestamp: '2025-07-15 08:41:02',
        type: 'success',
        operator: '系统自动处理',
        action: '已指令无人机退出禁飞区',
        notes: '无人机已在8秒内退出禁飞区，当前状态正常'
      },
      {
        timestamp: '2025-07-15 08:45:30',
        type: 'info',
        operator: '管理员Qin',
        action: '已记录违规事件，将进行原因分析',
        notes: '初步判断为GPS定位偏差导致'
      }
    ]
  }
])

// 页面状态与参数
const selectedSeverity = ref('all')
const selectedType = ref('all')
const dateRange = ref([])
const filteredAlerts = ref([...alerts.value])
const currentPage = ref(1)
const pageSize = ref(10)
const isRefreshing = ref(false)
const tableLoading = ref(false)
const detailVisible = ref(false)
const handleVisible = ref(false)
const selectedAlert = ref(null)
const isHandling = ref(false)
const selectedRows = ref([]) // 表格选中的行
const batchHandleVisible = ref(false)
const isBatchHandling = ref(false)
const chartTimeRange = ref('7d')
const chartData = ref({
  series: []
})

// 表单引用
const handleFormRef = ref(null)
const batchFormRef = ref(null)

// 处理表单数据
const handleForm = reactive({
  method: 'auto',
  notes: '',
  result: 'resolved'
})

// 批量处理表单数据
const batchHandleForm = reactive({
  method: 'auto',
  notes: '',
  result: 'resolved'
})

// 表单验证规则
const handleFormRules = {
  notes: [
    { required: true, message: '请输入处理备注', trigger: 'blur' },
    { min: 5, message: '备注长度不能少于5个字符', trigger: 'blur' }
  ],
  method: [
    { required: true, message: '请选择处理方式', trigger: 'change' }
  ],
  result: [
    { required: true, message: '请选择处理结果', trigger: 'change' }
  ]
}

// 批量处理表单验证规则
const batchHandleRules = {
  notes: [
    { required: true, message: '请输入处理备注', trigger: 'blur' },
    { min: 5, message: '备注长度不能少于5个字符', trigger: 'blur' }
  ],
  method: [
    { required: true, message: '请选择处理方式', trigger: 'change' }
  ],
  result: [
    { required: true, message: '请选择处理结果', trigger: 'change' }
  ]
}

// 计算属性：告警统计
const criticalAlerts = computed(() => {
  return alerts.value.filter(alert => alert.severity === 'CRITICAL' && alert.status === 'pending').length
})

const highAlerts = computed(() => {
  return alerts.value.filter(alert => alert.severity === 'HIGH' && alert.status === 'pending').length
})

const mediumAlerts = computed(() => {
  return alerts.value.filter(alert => alert.severity === 'MEDIUM' && alert.status === 'pending').length
})

const lowAlerts = computed(() => {
  return alerts.value.filter(alert => alert.severity === 'LOW' && alert.status === 'pending').length
})

const totalAlerts = computed(() => {
  return alerts.value.length
})

// 是否有未处理的告警
const hasPendingAlerts = computed(() => {
  return alerts.value.some(alert => alert.status === 'pending')
})

// 可自动处理的告警
const hasAutoResolvable = computed(() => {
  return filteredAlerts.value.some(alert => 
    alert.status === 'pending' && 
    (alert.severity === 'MEDIUM' || alert.severity === 'LOW')
  )
})

// 进度百分比（用于可视化展示）
const criticalProgress = computed(() => {
  const total = alerts.value.filter(alert => alert.severity === 'CRITICAL').length
  return total > 0 ? (criticalAlerts.value / total) * 100 : 0
})

const highProgress = computed(() => {
  const total = alerts.value.filter(alert => alert.severity === 'HIGH').length
  return total > 0 ? (highAlerts.value / total) * 100 : 0
})

const mediumProgress = computed(() => {
  const total = alerts.value.filter(alert => alert.severity === 'MEDIUM').length
  return total > 0 ? (mediumAlerts.value / total) * 100 : 0
})

const lowProgress = computed(() => {
  const total = alerts.value.filter(alert => alert.severity === 'LOW').length
  return total > 0 ? (lowAlerts.value / total) * 100 : 0
})

// 告警级别文本转换
const getSeverityText = (severity) => {
  const textMap = {
    'CRITICAL': '紧急告警',
    'HIGH': '高级告警',
    'MEDIUM': '中级告警',
    'LOW': '低级告警'
  }
  return textMap[severity] || severity
}

// 告警级别标签类型
const getSeverityTagType = (severity) => {
  const typeMap = {
    'CRITICAL': 'danger',
    'HIGH': 'warning',
    'MEDIUM': 'primary',
    'LOW': 'info'
  }
  return typeMap[severity] || 'info'
}

// 告警类型文本转换
const getTypeText = (type) => {
  const textMap = {
    'flight': '飞行安全',
    'device': '设备状态',
    'environment': '环境风险',
    'task': '任务异常'
  }
  return textMap[type] || type
}

// 告警状态文本转换
const getStatusText = (status) => {
  const textMap = {
    'pending': '待处理',
    'processing': '处理中',
    'processed': '已处理',
    'ignored': '已忽略'
  }
  return textMap[status] || status
}

// 告警状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'processing': 'info',
    'processed': 'success',
    'ignored': 'danger'
  }
  return typeMap[status] || 'info'
}

// 筛选告警
const filterAlerts = () => {
  tableLoading.value = true
  
  setTimeout(() => {
    let result = [...alerts.value]
    
    // 按级别筛选
    if (selectedSeverity.value !== 'all') {
      result = result.filter(alert => alert.severity === selectedSeverity.value)
    }
    
    // 按类型筛选
    if (selectedType.value !== 'all') {
      result = result.filter(alert => alert.type === selectedType.value)
    }
    
    // 按时间范围筛选
    if (dateRange.value && dateRange.value.length === 2) {
      const start = new Date(dateRange.value[0])
      const end = new Date(dateRange.value[1])
      result = result.filter(alert => {
        const time = new Date(alert.timestamp)
        return time >= start && time <= end
      })
    }
    
    filteredAlerts.value = result
    currentPage.value = 1 // 重置到第一页
    tableLoading.value = false
  }, 500)
}

// 刷新告警数据
const refreshAlerts = () => {
  isRefreshing.value = true
  
  // 模拟数据刷新
  setTimeout(() => {
    // 随机生成一个新告警
    const newAlert = generateRandomAlert()
    alerts.value.unshift(newAlert)
    
    // 重新应用筛选
    filterAlerts()
    // 刷新图表数据
    refreshChartData()
    
    isRefreshing.value = false
    ElMessage.success('告警数据已刷新')
  }, 800)
}

// 生成随机告警（模拟实时告警）
const generateRandomAlert = () => {
  const severities = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW']
  const types = ['flight', 'device', 'environment', 'task']
  const sources = ['无人机传感器', '空域监控系统', '气象服务', '任务管理器']
  const titles = [
    '无人机UAV-xxx通讯中断',
    '东南部区域降雨预警',
    '任务TSK-xxx路径偏离',
    '无人机UAV-xxx电机温度过高',
    '禁飞区边界异常接近'
  ]
  
  const severity = severities[Math.floor(Math.random() * severities.length)]
  const type = types[Math.floor(Math.random() * types.length)]
  const source = sources[Math.floor(Math.random() * sources.length)]
  const title = titles[Math.floor(Math.random() * titles.length)].replace('xxx', Math.floor(Math.random() * 100).toString().padStart(3, '0'))
  
  return {
    id: `ALM-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}-${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`,
    severity,
    type,
    title,
    source,
    timestamp: new Date().toLocaleString(),
    status: 'pending',
    description: '这是一个新生成的告警，需要及时处理。',
    affectedDrones: [`UAV-${Math.floor(Math.random() * 100).toString().padStart(3, '0')}`],
    impactRange: '随机区域',
    potentialLoss: '未知，需要评估',
    relatedAlerts: [],
    recommendedSolution: '根据告警类型，建议采取相应措施处理。',
    handleRecords: []
  }
}

// 自动处理可自动解决的告警
const handleAutoResolve = () => {
  const autoResolvable = filteredAlerts.value.filter(
    alert => alert.status === 'pending' && 
             (alert.severity === 'MEDIUM' || alert.severity === 'LOW')
  )
  
  if (autoResolvable.length === 0) {
    ElMessage.info('没有可自动处理的告警')
    return
  }
  
  ElMessageBox.confirm(
    `确定要自动处理 ${autoResolvable.length} 个可自动解决的告警吗？`,
    '自动处理确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    tableLoading.value = true
    
    setTimeout(() => {
      autoResolvable.forEach(alert => {
        const index = alerts.value.findIndex(a => a.id === alert.id)
        if (index !== -1) {
          alerts.value[index].status = 'processed'
          alerts.value[index].handleRecords.push({
            timestamp: new Date().toLocaleString(),
            type: 'success',
            operator: '系统自动处理',
            action: `已采用推荐方案处理`,
            notes: '自动处理完成'
          })
        }
      })
      
      filterAlerts()
      tableLoading.value = false
      ElMessage.success(`已自动处理 ${autoResolvable.length} 个告警`)
    }, 1000)
  })
}

// 导出告警报告
const exportAlertReport = () => {
  isRefreshing.value = true
  
  setTimeout(() => {
    // 模拟生成CSV内容
    const headers = ['告警ID', '级别', '类型', '标题', '来源', '发生时间', '状态']
    const rows = filteredAlerts.value.map(alert => [
      alert.id,
      getSeverityText(alert.severity),
      getTypeText(alert.type),
      alert.title,
      alert.source,
      alert.timestamp,
      getStatusText(alert.status)
    ])
    
    // 构建CSV内容
    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.join(','))
    ].join('\n')
    
    // 创建下载链接
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.setAttribute('href', url)
    link.setAttribute('download', `告警报告_${new Date().toLocaleDateString()}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    isRefreshing.value = false
    ElMessage.success('告警报告导出成功')
  }, 1000)
}

// 查看告警详情
const viewAlertDetail = (alert) => {
  selectedAlert.value = { ...alert }
  detailVisible.value = true
}

// 点击行查看详情
const handleRowClick = (row) => {
  viewAlertDetail(row)
}

// 处理告警（列表中）
const handleAlert = (alert) => {
  selectedAlert.value = { ...alert }
  detailVisible.value = false
  handleVisible.value = true
  
  // 重置表单
  handleForm.method = 'auto'
  handleForm.notes = ''
  handleForm.result = 'resolved'
}

// 详情中处理告警
const handleAlertInDetail = () => {
  detailVisible.value = false
  handleVisible.value = true
}

// 采用推荐方案
const adoptRecommendedSolution = () => {
  if (!selectedAlert.value) return
  
  handleForm.method = 'auto'
  handleForm.notes = `采用系统推荐方案：${selectedAlert.value.recommendedSolution}`
  handleForm.result = 'resolved'
  
  detailVisible.value = false
  handleVisible.value = true
}

// 确认处理告警
const confirmHandleAlert = () => {
  if (!selectedAlert.value) return
  
  // 直接使用表单ref进行验证（修复核心）
  if (handleFormRef.value) {
    handleFormRef.value.validate((valid) => {
      if (!valid) return
      
      isHandling.value = true
      
      setTimeout(() => {
        // 更新告警状态
        const index = alerts.value.findIndex(a => a.id === selectedAlert.value.id)
        if (index !== -1) {
          alerts.value[index].status = 'processed'
          
          // 添加处理记录
          alerts.value[index].handleRecords.push({
            timestamp: new Date().toLocaleString(),
            type: handleForm.result === 'resolved' ? 'success' : 'warning',
            operator: '管理员Qin',
            action: `已${handleForm.method === 'auto' ? '采用推荐方案' : '手动'}处理`,
            notes: `处理结果：${getStatusText(handleForm.result)}。${handleForm.notes}`
          })
        }
        
        // 更新筛选列表
        filterAlerts()
        
        // 关闭弹窗
        handleVisible.value = false
        isHandling.value = false
        
        ElMessage.success('告警处理完成')
      }, 1500)
    })
  }
}

// 处理全部告警
const handleAllAlerts = () => {
  const pendingAlerts = filteredAlerts.value.filter(alert => alert.status === 'pending')
  if (pendingAlerts.length === 0) {
    ElMessage.info('没有待处理的告警')
    return
  }
  
  ElMessageBox.confirm(
    `确定要处理所有 ${pendingAlerts.length} 个待处理告警吗？`,
    '处理全部确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    tableLoading.value = true
    
    setTimeout(() => {
      pendingAlerts.forEach(alert => {
        const index = alerts.value.findIndex(a => a.id === alert.id)
        if (index !== -1) {
          alerts.value[index].status = 'processed'
          alerts.value[index].handleRecords.push({
            timestamp: new Date().toLocaleString(),
            type: 'success',
            operator: '管理员Qin',
            action: '批量处理',
            notes: '通过"处理全部"功能统一处理'
          })
        }
      })
      
      filterAlerts()
      tableLoading.value = false
      ElMessage.success(`已处理全部 ${pendingAlerts.length} 个待处理告警`)
    }, 1500)
  })
}

// 表格选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 批量处理告警
const handleBatchProcess = () => {
  if (selectedRows.value.length === 0) return
  
  batchHandleVisible.value = true
  // 重置批量处理表单
  batchHandleForm.method = 'auto'
  batchHandleForm.notes = ''
  batchHandleForm.result = 'resolved'
}

// 确认批量处理
const confirmBatchHandle = () => {
  // 使用表单ref进行验证
  if (batchFormRef.value) {
    batchFormRef.value.validate((valid) => {
      if (!valid) return
      
      isBatchHandling.value = true
      
      setTimeout(() => {
        selectedRows.value.forEach(alert => {
          const index = alerts.value.findIndex(a => a.id === alert.id)
          if (index !== -1) {
            alerts.value[index].status = 'processed'
            alerts.value[index].handleRecords.push({
              timestamp: new Date().toLocaleString(),
              type: 'success',
              operator: '管理员Qin',
              action: `批量${batchHandleForm.method === 'auto' ? '自动' : '手动'}处理`,
              notes: `处理结果：${getStatusText(batchHandleForm.result)}。${batchHandleForm.notes}`
            })
          }
        })
        
        // 更新筛选列表
        filterAlerts()
        // 清空选择
        selectedRows.value = []
        // 关闭弹窗
        batchHandleVisible.value = false
        isBatchHandling.value = false
        
        ElMessage.success(`已批量处理 ${selectedRows.value.length} 个告警`)
      }, 1500)
    })
  }
}

// 取消选择
const clearSelection = () => {
  selectedRows.value = []
}

// 分页相关方法
const handleSizeChange = (size) => {
  pageSize.value = size
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 关闭详情弹窗
const closeDetailDialog = () => {
  detailVisible.value = false
}

// 刷新图表数据
const refreshChartData = () => {
  // 生成模拟的趋势数据
  const days = parseInt(chartTimeRange.value)
  const data = []
  
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    const dateStr = date.toLocaleDateString()
    
    // 随机生成每天的告警数量
    const count = Math.floor(Math.random() * 20) + 1
    
    data.push({
      date: dateStr,
      count
    })
  }
  
  chartData.value.series = data
}

// 图表提示格式化
const chartTooltipFormatter = (params) => {
  return `
    <div class="chart-tooltip">
      <div class="tooltip-date">${params.date}</div>
      <div class="tooltip-value">告警数量: ${params.count}</div>
    </div>
  `
}

// 页面初始化
onMounted(() => {
  // 初始筛选
  filterAlerts()
  // 初始化图表数据
  refreshChartData()
  
  // 模拟定时告警推送
  const alertInterval = setInterval(() => {
    // 30%概率生成新告警
    if (Math.random() > 0.7) {
      const newAlert = generateRandomAlert()
      alerts.value.unshift(newAlert)
      filterAlerts()
      
      // 紧急告警显示通知
      if (newAlert.severity === 'CRITICAL') {
        ElNotification({
          title: '新紧急告警',
          message: newAlert.title,
          type: 'error',
          duration: 0, // 不自动关闭
          onClick: () => {
            viewAlertDetail(newAlert)
          }
        })
      }
    }
  }, 30000) // 每30秒检查一次
  
  // 清理函数
  return () => {
    clearInterval(alertInterval)
  }
})
</script>

<style scoped>

.bdr{
    margin-top: 15px;
}
/* 告警概览 */
.alarm-overview {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.overview-card {
  flex: 1;
  min-width: 200px;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 15px;
}

.overview-card.critical {
  border-left: 4px solid #F56C6C;
}

.overview-card.high {
  border-left: 4px solid #E6A23C;
}

.overview-card.medium {
  border-left: 4px solid #409EFF;
}

.overview-card.low {
  border-left: 4px solid #67C23A;
}

.overview-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.critical .overview-icon {
  background-color: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.high .overview-icon {
  background-color: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
}

.medium .overview-icon {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.low .overview-icon {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.overview-icon el-icon {
  font-size: 20px;
}

.overview-info {
  flex: 1;
}

.overview-value {
  font-size: 22px;
  font-weight: 500;
  color: #1f2329;
}

.overview-label {
  font-size: 14px;
  color: #606266;
}

.overview-progress {
  width: 80px;
}

/* 告警图表 */
.alarm-chart {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
  width: 100%;
}

/* 告警列表控制区 */
.alarm-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-group {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.filter-select {
  width: 140px;
}

.filter-date {
  width: 300px;
}

.action-group {
  display: flex;
  gap: 10px;
}

/* 告警列表 */
.alarm-list {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 15px;
}

.alarm-table {
  width: 100%;
  margin-bottom: 15px;
}

.view-btn {
  color: #409EFF;
}

.pagination {
  margin-top: 15px;
  text-align: right;
}

/* 批量操作栏 */
.batch-operation {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.count-number {
  color: #409EFF;
  font-weight: bold;
}

/* 告警详情弹窗 */
.alert-detail {
  padding: 10px 0;
}

.detail-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.detail-title {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 500;
}

.detail-severity {
  margin-top: 2px;
}

.detail-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  color: #606266;
  font-size: 14px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.content-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 10px;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 5px;
}

.section-title::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 14px;
  background-color: #409EFF;
  border-radius: 2px;
}

.section-content {
  color: #606266;
  line-height: 1.6;
}

.impact-descriptions {
  margin-top: 5px;
}

.solution-card {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  margin-top: 5px;
}

.solution-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-weight: 500;
}

.solution-content {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 10px;
}

.timeline-content {
  padding: 5px 0;
}

.record-operator {
  font-weight: 500;
  margin-bottom: 3px;
}

.record-action {
  color: #303133;
  margin-bottom: 3px;
}

.record-notes {
  color: #606266;
  font-size: 13px;
}

/* 处理告警弹窗 */
.handle-alert {
  padding: 10px 0;
}

.handle-info {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.handle-info p {
  margin: 5px 0;
}

.handle-form {
  margin-top: 10px;
}

/* 批量处理弹窗 */
.batch-handle-form {
  padding: 10px 0;
}

.batch-count {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .filter-date {
    width: 250px;
  }
}

@media (max-width: 992px) {
  .alarm-overview {
    flex-direction: column;
  }
  
  .overview-card {
    width: 100%;
  }
  
  .filter-group {
    width: 100%;
  }
  
  .filter-date {
    width: 100%;
    flex-grow: 1;
  }
  
  .action-group {
    width: 100%;
    justify-content: flex-end;
  }
}

@media (max-width: 768px) {
  .filter-select {
    width: 100%;
  }
  
  .detail-meta {
    flex-direction: column;
    gap: 5px;
  }
  
  .meta-item {
    width: 100%;
  }
  
  .chart-container {
    height: 200px;
  }
}
</style>